import axios from 'axios'
import {Message} from 'element-ui';
import router from "@/router";

axios.defaults.baseURL = '/api/'
// 设置请求超时时间
axios.defaults.timeout = 10000;
// 设置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
// 请求前拦截
axios.interceptors.request.use(
    config => {
        let token = sessionStorage.getItem("token")
        if (token) {
            config.headers.common['token'] = token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    });
// 响应拦截
axios.interceptors.response.use(response => {
    const {data} = response
    const {code, msg} = data
    if (code === '02') {
        Message.error(msg || '系统异常')
    } else if (code === '03') {
        sessionStorage.clear()
        router.replace('login')
    }

    return response.data
}, error => {
    if (error.response) {
        return Promise.reject(error)
    } else {
        if (!window.navigator.online) {
            //=>断网处理
            return;
        }
        return Promise.reject(error)
    }
})

/**
 * get方法封装
 * @param url
 * @param params
 * @returns {Promise<unknown>}
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * post方法封装
 * @param url
 * @param params
 * @returns {Promise<unknown>}
 */
export function post(url, params) {
    let token = sessionStorage.getItem("token")
    return axios.post(url, {...params, token,},{timeout: 1000 * 60 });
}


/**
 * upload 上传
 * @param url
 * @param data fromData
 * @returns {Promise<unknown>}
 */
export function upload(url, data) {
    data.append('token', sessionStorage.getItem("token"))
    return axios.post(url, data, {timeout: 1000 * 60 * 60});
}

